package com.cade.agriculturemall.view.personalCenter.editAddress;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.addresspicker.huichao.addresspickerlibrary.CityPickerDialog;
import com.addresspicker.huichao.addresspickerlibrary.InitAreaTask;
import com.addresspicker.huichao.addresspickerlibrary.Util;
import com.addresspicker.huichao.addresspickerlibrary.address.City;
import com.addresspicker.huichao.addresspickerlibrary.address.County;
import com.addresspicker.huichao.addresspickerlibrary.address.Province;
import com.cade.agriculturemall.R;
import com.cade.agriculturemall.base.BaseActivity;
import com.cade.agriculturemall.bean.AddressBean;
import com.cade.agriculturemall.bean.CityChildsBean;
import com.cade.agriculturemall.bean.CountyChildsBean;
import com.cade.agriculturemall.bean.StreetChildsBean;
import com.cade.agriculturemall.model.AddressEntity;
import com.cade.agriculturemall.utils.DataHelper;
import com.cade.agriculturemall.widget.wheel.adapter.StressPickerDialog;

import java.util.ArrayList;
import java.util.List;

public class EditAddressActivity extends BaseActivity<EditAddressContract.IPresenter> implements EditAddressContract.IView, View.OnClickListener {
    private TextView tvArea;
    private TextView tvStress;
    private ImageView imgPhone;
    private EditText etPhone;
    private EditText etDetail;
    private EditText etName;
    private List<AddressBean> addressBeans;
    private Province selectedProvince;
    private City selectedCity;
    private County selectedCounty;
    private StreetChildsBean selectedStreet;
    private StreetChildsBean streetChild;
    List<StreetChildsBean> street = new ArrayList<>();
    private AddressEntity mEntity = new AddressEntity();
    private Switch mSwitch;   //"1" 默认  "2" 否
    private String type;//type=1修改   type=2 添加
    private String addressId = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        Toolbar toolbar = (Toolbar) findViewById(R.id.addaddress_toolbar);
        setSupportActionBar(toolbar);
        toolbar.setTitle("");
        //关键下面两句话，设置了回退按钮，及点击事件的效果
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView tvTitle = (TextView) findViewById(R.id.toolbar_addaddress_title);
        if (type.equals("2")) {
            tvTitle.setText("添加新地址");
        } else if (type.equals("1")) {
            tvTitle.setText("修改地址");
        }
    }


    @Override
    public void setupView() {
        TextView tvDelete = (TextView) findViewById(R.id.add_address_delete);
        tvArea = (TextView) findViewById(R.id.add_address_tv_distinct);
        tvStress = (TextView) findViewById(R.id.add_address_tv_stress);
        LinearLayout llArea = (LinearLayout) findViewById(R.id.add_address_ll_distinct);
        LinearLayout llStress = (LinearLayout) findViewById(R.id.add_address_ll_stress);
        imgPhone = (ImageView) findViewById(R.id.add_address_img);
        etPhone = (EditText) findViewById(R.id.add_address_tv_phone);
        etDetail = (EditText) findViewById(R.id.add_address_tv_digital_address);
        etName = (EditText) findViewById(R.id.add_address_tv_name);
        etDetail.setSelection(etDetail.getText().length());
        mSwitch = (Switch) findViewById(R.id.add_address_switch);

        Button btnSave = (Button) findViewById(R.id.addaddress_toolbar_btn_save);
        btnSave.setOnClickListener(this);
        llArea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAddressDialog();
            }
        });
        llStress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showStressDialog();
            }
        });
        imgPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                跳转到通讯录界面
                Uri uri = Uri.parse("content://contacts/people");
                Intent intent = new Intent(Intent.ACTION_PICK, uri);
                startActivityForResult(intent, 0);
            }
        });
        tvDelete.setOnClickListener(this);
        type = getIntent().getStringExtra("type");
        addressId = getIntent().getStringExtra("AddressObjectId");
        if (type != null) {
            switch (type) {
                case "2":
                    tvDelete.setVisibility(View.GONE);
                    break;
                case "1":
                    tvDelete.setVisibility(View.VISIBLE);
                    mPresenter.downAddress(addressId);
                    break;

            }
        }
        tvArea.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                tvStress.setText("");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.addaddress_toolbar_btn_save:
                mEntity.setAddress(etDetail.getText().toString());
                mEntity.setMobile(etPhone.getText().toString());
                mEntity.setContractor(etName.getText().toString());
                mEntity.setIsfirst(mSwitch.isChecked() == true ? "1" : "2");
                collectData();
                break;
            case R.id.add_address_delete:
//                删除地址
                AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
                builder.setMessage("确认要删除改地址吗？");
                builder.setNegativeButton("取消", null);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mPresenter.deleteAddress(addressId);
                    }
                });
                android.app.AlertDialog dialog = builder.create();
                dialog.show();
                break;
        }
    }

    //      搜集
    private void collectData() {
        String stress = mEntity.getStress();
        if (TextUtils.isEmpty(mEntity.getContractor())) {
            Toast.makeText(getApplication(), "收货人姓名至少2字符", Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(mEntity.getMobile())) {
            Toast.makeText(mActivity, "请填写联系电话", Toast.LENGTH_SHORT).show();
        } else if (mEntity.getMobile().length() != 11) {
            Toast.makeText(this, "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(tvArea.getText().toString())) {
            Toast.makeText(mActivity, "请选择地区", Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(stress)) {
            Toast.makeText(mActivity, "请选择街道", Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isEmpty(mEntity.getAddress())) {
            Toast.makeText(mActivity, "请填写详细地址", Toast.LENGTH_SHORT).show();
        } else {
            mPresenter.upLoadAddress(addressId, mEntity);
        }
    }

    @Override
    public void setupEvent() {

    }

    //修改 获取数据
    @Override
    public void upLoadAddressData(final AddressEntity entity) {
        mEntity = entity;
        if (mEntity != null) {
            getStressAddress(mEntity.getCityId());
            etName.setText(mEntity.getContractor());
            etPhone.setText(mEntity.getMobile());
            String procincecity = mEntity.getProvince() + mEntity.getCity();
            String procincecounty = procincecity + mEntity.getCounty();
            tvArea.setText(mEntity.getCounty() == null ? procincecity : procincecounty);
            tvStress.setText(mEntity.getStress());
            etDetail.setText(mEntity.getAddress());
            mSwitch.setChecked(mEntity.getIsfirst().equals("1") ? true : false);
            mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    entity.setIsfirst(isChecked ? "1" : "2");
                }
            });
        }
    }

    @Override
    public void setupData() {
        addressBeans = DataHelper.getAddress(this);
        loadAddressData();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }

    private ArrayList<Province> provinces;
    private ArrayList<StreetChildsBean> stress;
    private Dialog progressDialog;

    //
    @Override
    public EditAddressContract.IPresenter setupPresenter() {
        return new EditAddressPresenter(this);
    }

    public void loadAddressData() {
        if (provinces == null) {
            provinces = new ArrayList<>();
        }
        if (provinces.size() > 0) {
//            showAddressDialog();
        } else {
            //没有地址数据，就去初始化
            InitAreaTask initAreaTask = new InitAreaTask(this, provinces);
            initAreaTask.execute(0);
            initAreaTask.setOnLoadingAddressListener(new InitAreaTask.onLoadingAddressListener() {
                @Override
                public void onLoadFinished() {//加载完成的监听
                    progressDialog.dismiss();
//                    showAddressDialog();
                }

                @Override
                public void onLoading() {//加载中监听
                    progressDialog = Util.createLoadingDialog(getApplication(), "请稍等...", true, 0);
//                    progressDialog.show();
                }
            });
        }
    }

    @Override
    public void upLoadSuccess() {
        goBack();
        Toast.makeText(mActivity, "保存成功", Toast.LENGTH_SHORT).show();
    }

    //          dialog 地区 点击事件
    @Override
    public void showAddressDialog() {//初始化地址数据后，显示地址选择框
        CityPickerDialog dialog;
        if (TextUtils.isEmpty(tvArea.getText())) {
            dialog = new CityPickerDialog(this, provinces, null, null, null,
                    new CityPickerDialog.onCityPickedListener() {
                        @Override
                        public void onPicked(Province selectProvince,
                                             City selectCity, County selectCounty) {
                            append(selectProvince, selectCity, selectCounty);
                        }
                    });
            dialog.show();
        } else {
            CityPickerDialog cityPickerDialog = new CityPickerDialog(
                    this, provinces, selectedProvince, selectedCity, selectedCounty,
                    new CityPickerDialog.onCityPickedListener() {
                        @Override
                        public void onPicked(Province province, City city, County county) {
                            append(province, city, county);
                        }
                    });
            cityPickerDialog.show();
        }
    }

    public void append(Province province, City city, County county) {
        selectedProvince = province;
        selectedCity = city;
        selectedCounty = county;
        mEntity.setCity(selectedCity.getAreaName());
        mEntity.setCityId(selectedCity.getAreaId());
        mEntity.setProvince(selectedProvince.getAreaName());
        StringBuilder address = new StringBuilder();
        address.append(
                province != null ? province
                        .getAreaName() : "")
                .append(city != null ? city
                        .getAreaName() : "");
        if (county != null) {
            String areaName = county.getAreaName();
            if (areaName != null) {
                address.append(areaName);
                mEntity.setCounty(areaName);
                mEntity.setCity(selectedCity.getAreaName());
                mEntity.setCityId(selectedCity.getAreaId());
                mEntity.setCountyId(selectedCounty.getAreaId());
                String countId = county.getAreaId();
                getStressAddress(countId);
            }
        } else {
            String cityId = city.getAreaId();
            getStressAddress(cityId);
        }
        tvArea.setText(address.toString());
    }

    private void showStressDialog() {
        if (!TextUtils.isEmpty(tvArea.getText())) {
            if (street != null) {
                new StressPickerDialog(this, street, null, new StressPickerDialog.onCityPickedListener() {
                    @Override
                    public void onPicked(StreetChildsBean selectStreet) {
                        selectedStreet = selectStreet;
                        mEntity.setStress(selectStreet.getName());
                        tvStress.setText(selectStreet.getName());
                    }
                }).show();
            } else {
                new StressPickerDialog(this, street, selectedStreet, new StressPickerDialog.onCityPickedListener() {
                    @Override
                    public void onPicked(StreetChildsBean selectStreet) {
                        selectedStreet = selectStreet;
                        mEntity.setStress(selectStreet.getName());
                        tvStress.setText(selectStreet.getName());
                    }
                });
            }
        } else {
            Toast.makeText(mActivity, "请选择地区", Toast.LENGTH_SHORT).show();
        }
    }


    public void getStressAddress(String countId) {
//        遍历
        List<CityChildsBean> city;
        for (int i = 0; i < addressBeans.size(); i++) {
            if (countId.substring(0, 2).equals(addressBeans.get(i).getCode())) {
                city = addressBeans.get(i).getChilds();
                if (city != null) {
                    for (int j = 0; j < city.size(); j++) {
                        if (countId.substring(0, 4).equals(city.get(j).getCode())) {
                            List<CountyChildsBean> country = new ArrayList<>();
                            country.addAll(city.get(j).getChilds());
                            for (int k = 0; k < country.size(); k++) {
                                if (countId.equals(country.get(k).getCode())) {
                                    street.addAll(country.get(k).getChilds());
                                    street = country.get(k).getChilds();
                                }
                            }
                        }
                    }
                }
            }

        }
    }

    /**
     * 跳转到通讯录获取用户名称和手机号码
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    /*
   * 跳转联系人列表的回调函数
   * */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 0:
                if (data == null) {
                    return;
                }
                //处理返回的data,获取选择的联系人信息
                Uri uri = data.getData();
                String[] contacts = getPhoneContacts(uri);
//                et_name.setText(contacts[0]);
                String phone = contacts[1].replace(" ", "").replace("-", "");
                etPhone.setText(phone);
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private String[] getPhoneContacts(Uri uri) {
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phone != null) {
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phone.close();
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }

}
